<template>
  <div>
    <NavigationBar />
    <div class="page-container">
      <div class="pet-adoption">
        <h1>宠物领养</h1>
        <div class="filters">
          <div class="filter-group">
            <label for="type">宠物类型：</label>
            <select v-model="filters.type" id="type">
              <option value="">全部</option>
              <option value="cat">猫</option>
              <option value="dog">狗</option>
            </select>
          </div>
          <div class="filter-group">
            <label for="favorite">收藏状态：</label>
            <select v-model="filters.favorite" id="favorite">
              <option value="">全部</option>
              <option value="unfavorited">未收藏</option>
              <option value="favorited">已收藏</option>
            </select>
          </div>
          <div class="filter-group">
            <label for="gender">性别：</label>
            <select v-model="filters.gender" id="gender">
              <option value="">全部</option>
              <option value="雄">雄性</option>
              <option value="雌">雌性</option>
            </select>
          </div>
          <div class="filter-group">
            <label for="size">体型：</label>
            <select v-model="filters.size" id="size">
              <option value="">全部</option>
              <option value="small">小型</option>
              <option value="medium">中型</option>
              <option value="large">大型</option>
            </select>
          </div>
        </div>
        <div class="pet-list">
          <div 
            v-for="pet in filteredPets" 
            :key="pet.id" 
            class="pet-item" 
            @mouseover="hoveredPet = pet"
            @mouseleave="hoveredPet = null"
            :class="{ lost: pet.status === 'lost' }"
          >
            <img :src="getImageUrl(pet.image)" alt="宠物图片" class="pet-image" />
            <h2>{{ pet.name }}</h2>
            <p>{{ pet.description }}</p>
            <div class="pet-actions">
              <button class="adopt-btn" @click="showPetDetails(pet)">领养</button>
              <button 
                class="favorite-btn" 
                @click.stop="toggleFavorite(pet)" 
                :class="{ 'favorited': isFavorited(pet) }"
              >
                ♥
              </button>
            </div>
            <div v-if="hoveredPet === pet" class="hover-overlay">
              <p>点击领养按钮了解更多</p>
            </div>
          </div>
        </div>
        <div class="pagination" v-if="filteredPets.length > 0">
          <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
          <span>{{ currentPage }} / {{ totalPages }}</span>
          <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
        </div>
        <div v-else class="no-pets">
          <p>没有找到符合条件的宠物</p>
        </div>
      </div>
    </div>
    <Footer />

    <!-- 宠物详情弹窗 -->
    <div v-if="selectedPet" class="pet-modal" @click.self="selectedPet = null">
      <div class="modal-content">
        <button class="close-btn" @click="selectedPet = null">×</button>
        <img :src="getImageUrl(selectedPet.image)" :alt="selectedPet.name" class="modal-image" />
        <div class="modal-info">
          <h2>{{ selectedPet.name }}</h2>
          <div class="info-row">
            <span class="info-label">类型：</span>
            <span>{{ selectedPet.type === 'cat' ? '猫' : '狗' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">性别：</span>
            <span>{{ selectedPet.gender === '雄' ? '雄性' : '雌性' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">年龄：</span>
            <span>{{ selectedPet.age }}岁</span>
          </div>
          <div class="info-row">
            <span class="info-label">体型：</span>
            <span>
              {{ selectedPet.size === 'small' ? '小型' :
              selectedPet.size === 'medium' ? '中型' : '大型' }}
            </span>
          </div>
          <p class="modal-description">{{ selectedPet.description }}</p>

          <!-- 添加领养表单 -->
          <form @submit.prevent="submitAdoptionForm" class="adoption-form">
            <h3>领养申请表</h3>
            <div class="form-group">
              <label for="name">姓名 *</label>
              <input type="text" id="name" v-model="formData.name" required>
            </div>

            <div class="form-group">
              <label for="phone">联系电话 *</label>
              <input type="tel" id="phone" v-model="formData.phone" required>
            </div>

            <div class="form-group">
              <label for="email">电子邮箱</label>
              <input type="email" id="email" v-model="formData.email">
            </div>

            <div class="form-group">
              <label for="address">居住地址 *</label>
              <input type="text" id="address" v-model="formData.address" required>
            </div>

            <div class="form-group">
              <label for="housing">住房类型 *</label>
              <select id="housing" v-model="formData.housing" required>
                <option value="">请选择</option>
                <option value="own">自有房产</option>
                <option value="rent">租房</option>
                <option value="other">其他</option>
              </select>
            </div>

            <div class="form-group">
              <label for="experience">养宠经验 *</label>
              <select id="experience" v-model="formData.experience" required>
                <option value="">请选择</option>
                <option value="none">无经验</option>
                <option value="some">有一些经验</option>
                <option value="rich">经验丰富</option>
              </select>
            </div>

            <div class="form-group">
              <label for="monthlySalary">月收入（元） *</label>
              <input type="number" id="monthlySalary" v-model.number="formData.monthlySalary" min="0" required>
              <span v-if="validationErrors.salary" class="error-message">{{ validationErrors.salary }}</span>
            </div>

            <div class="form-group">
              <label for="employmentStatus">就业状态 *</label>
              <select id="employmentStatus" v-model="formData.employmentStatus" required>
                <option value="employed">在职</option>
                <option value="unemployed">待业</option>
                <option value="student">学生</option>
                <option value="retired">退休</option>
              </select>
            </div>

            <div class="form-group">
              <label for="householdMembers">同住人数 *</label>
              <input type="number" id="householdMembers" v-model.number="formData.householdMembers" min="1" required>
            </div>

            <div class="form-group">
              <label class="checkbox-label">
                <input type="checkbox" v-model="formData.hasDebt">
                我目前有未偿还的债务（房贷、车贷、消费贷等）
              </label>
            </div>

            <div class="form-group">
              <label class="checkbox-label">
                <input type="checkbox" v-model="formData.hasProperty">
                我拥有自有房产（非租房）
              </label>
            </div>

            <div class="form-group full-width">
              <label for="reason">领养原因 *</label>
              <textarea id="reason" v-model="formData.reason" required></textarea>
            </div>

            <div class="form-group full-width">
              <label class="checkbox-label">
                <input type="checkbox" v-model="formData.agreement" required>
                我已阅读并同意<a href="#" @click.prevent="showAgreement">《领养协议》</a>
              </label>
            </div>

            <div class="form-actions">
              <button type="button" class="cancel-btn" @click="selectedPet = null">取消</button>
              <button type="submit" class="submit-btn">提交申请</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 领养协议弹窗 -->
    <div v-if="showAgreementModal" class="modal-overlay" @click.self="showAgreementModal = false">
      <div class="modal-content">
        <button class="close-btn" @click="showAgreementModal = false">×</button>
        <h3>领养协议</h3>
        <div class="agreement-text">
          <p>1. 领养人必须年满18周岁，具有完全民事行为能力。</p>
          <p>2. 领养人需提供真实有效的身份证明和居住信息。</p>
          <p>3. 领养人承诺为宠物提供安全、健康的生活环境，保证宠物的基本福利。</p>
          <p>4. 领养人同意定期为宠物进行健康检查、疫苗接种和驱虫。</p>
          <p>5. 领养人承诺不虐待、不遗弃宠物，如因特殊原因无法继续饲养，应将其送回本机构。</p>
          <p>6. 领养人同意机构工作人员进行不定期的回访，了解宠物生活状况。</p>
          <p>7. 未经机构同意，领养人不得将宠物转赠或出售给第三方。</p>
          <p>8. 如发现领养人有违反协议的行为，机构有权收回宠物。</p>
        </div>
        <button class="agree-btn" @click="agreeToTerms">我已阅读并同意</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import Footer from '@/components/Footer.vue'
import NavigationBar from '@/components/NavigationBar.vue'
import { pets } from '@/data/petsData.js'

const router = useRouter()

// 响应式数据
const filters = ref({
  type: '',
  favorite: '',
  gender: '',
  size: ''
})
const hoveredPet = ref(null)
const currentPage = ref(1)
const itemsPerPage = 6
const favorites = ref(JSON.parse(localStorage.getItem('petFavorites')) || [])
const selectedPet = ref(null)
const showAgreementModal = ref(false)
const formData = ref({
  name: '',
  phone: '',
  email: '',
  address: '',
  housing: '',
  experience: '',
  reason: '',
  agreement: false,
  monthlySalary: 3000,
  hasDebt: false,
  hasProperty: false,
  employmentStatus: 'employed',
  householdMembers: 1
})
const validationErrors = ref({
  salary: '',
  debtProperty: ''
})

// 计算属性
const filteredPets = computed(() => {
  let filtered = [...pets]

  if (filters.value.type) {
    filtered = filtered.filter(pet => pet.type === filters.value.type)
  }

  if (filters.value.favorite === 'favorited') {
    filtered = filtered.filter(pet => isFavorited(pet))
  } else if (filters.value.favorite === 'unfavorited') {
    filtered = filtered.filter(pet => !isFavorited(pet))
  }

  if (filters.value.gender) {
    filtered = filtered.filter(pet => pet.gender === filters.value.gender)
  }

  if (filters.value.size) {
    filtered = filtered.filter(pet => pet.size === filters.value.size)
  }

  return filtered.slice((currentPage.value - 1) * itemsPerPage, currentPage.value * itemsPerPage)
})

const totalPages = computed(() => {
  const filteredLength = pets.filter(pet => {
    let match = true
    if (filters.value.type && pet.type !== filters.value.type) match = false
    if (filters.value.favorite === 'favorited' && !isFavorited(pet)) match = false
    if (filters.value.favorite === 'unfavorited' && isFavorited(pet)) match = false
    if (filters.value.gender && pet.gender !== filters.value.gender) match = false
    if (filters.value.size && pet.size !== filters.value.size) match = false
    return match
  }).length
  return Math.ceil(filteredLength / itemsPerPage)
})

// 方法
const getImageUrl = (imageName) => {
  return new URL(`/src/assets/images/${imageName}`, import.meta.url).href
}

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
  }
}

const toggleFavorite = (pet) => {
  const index = favorites.value.findIndex(fav => fav.id === pet.id)
  if (index === -1) {
    favorites.value.push(pet)
  } else {
    favorites.value.splice(index, 1)
  }
  localStorage.setItem('petFavorites', JSON.stringify(favorites.value))
}

const isFavorited = (pet) => {
  return favorites.value.some(fav => fav.id === pet.id)
}

const showPetDetails = (pet) => {
  selectedPet.value = pet
}

const showAgreement = () => {
  showAgreementModal.value = true
}

const agreeToTerms = () => {
  formData.value.agreement = true
  showAgreementModal.value = false
}

const validateForm = () => {
  let isValid = true
  
  // 验证月收入
  if (formData.value.monthlySalary < 3000) {
    validationErrors.value.salary = '月收入需≥3000元才能领养'
    isValid = false
  } else {
    validationErrors.value.salary = ''
  }
  
  // 验证负债和房产
  if (formData.value.hasDebt && !formData.value.hasProperty) {
    validationErrors.value.debtProperty = '负债情况下需拥有自有房产才能领养'
    isValid = false
  } else {
    validationErrors.value.debtProperty = ''
  }
  
  // 验证就业状态
  if (formData.value.employmentStatus === 'unemployed') {
    if (formData.value.monthlySalary < 5000) {
      validationErrors.value.salary = '待业状态需证明有≥5000元/月的稳定收入来源'
      isValid = false
    }
  }
  
  return isValid
}

const submitAdoptionForm = () => {
  if (!validateForm()) {
    return
  }
  
  if (!formData.value.agreement) {
    alert('请先同意领养协议')
    return
  }

  // 保存表单数据
  localStorage.setItem('adoptionFormData', JSON.stringify(formData.value))

  // 跳转到领养进度页面
  router.push({
    name: 'PetAdoptionRegistration',
    params: { petId: selectedPet.value.id },
    query: {
      petName: selectedPet.value.name,
      petImage: selectedPet.value.image,
      petType: selectedPet.value.type,
      petGender: selectedPet.value.gender,
      petAge: selectedPet.value.age
    }
  })
}

// 初始化加载保存的表单数据
onMounted(() => {
  const savedFormData = localStorage.getItem('adoptionFormData')
  if (savedFormData) {
    formData.value = {
      ...formData.value,
      ...JSON.parse(savedFormData)
    }
  }
})
</script>

<style scoped>
/* 保持原有样式不变 */
.page-container {
  padding: 20px 0;
  min-height: calc(100vh - 120px);
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.pet-adoption {
  margin: 0 auto;
  padding: 20px;
  text-align: center;
  font-family: 'Arial', sans-serif;
  background-color: white;
  border-radius: 15px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
  width: 90%;
}

h1 {
  color: #4a7c59;
  margin-bottom: 25px;
  font-size: 2.2rem;
}

.filters {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  margin-bottom: 25px;
  gap: 15px;
}

.filter-group {
  display: flex;
  align-items: center;
  margin: 0 10px;
}

.filter-group label {
  margin-right: 8px;
  font-weight: bold;
  color: #4a7c59;
  font-size: 0.95rem;
  white-space: nowrap;
}

select {
  padding: 8px 15px;
  border-radius: 8px;
  border: 1px solid #ddd;
  background-color: white;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.3s;
  min-width: 100px;
}

select:focus {
  outline: none;
  border-color: #4a7c59;
  box-shadow: 0 0 0 2px rgba(74, 124, 89, 0.2);
}

.pet-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 25px;
  margin-bottom: 30px;
}

.pet-item {
  position: relative;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  background-color: white;
  padding-bottom: 15px;
}

.pet-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.12);
}

.pet-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-bottom: 1px solid #eee;
}

.pet-item h2 {
  font-size: 1.3rem;
  color: #4a7c59;
  margin: 12px 0 8px;
  padding: 0 10px;
}

.pet-item p {
  font-size: 0.9rem;
  color: #666;
  margin: 0 15px 15px;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  display: -moz-box;
  -moz-line-clamp: 2;
  -moz-box-orient: vertical;
  display: box;
  line-clamp: 2;
  box-orient: vertical;
}

.pet-actions {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 12px;
  position: relative;
  z-index: 2;
}

.adopt-btn {
  padding: 8px 20px;
  background-color: #4a7c59;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 0.9rem;
}

.adopt-btn:hover {
  background-color: #3a6a49;
  transform: translateY(-2px);
}

.favorite-btn {
  padding: 0;
  width: 36px;
  height: 36px;
  background-color: transparent;
  border: 1px solid #ddd;
  border-radius: 50%;
  cursor: pointer;
  font-size: 1.1rem;
  color: #ccc;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.favorite-btn.favorited {
  color: #ff4757;
  border-color: #ff4757;
  background-color: rgba(255, 71, 87, 0.1);
}

.favorite-btn:hover {
  transform: scale(1.1);
}

.hover-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
  pointer-events: none;
  z-index: 1;
  border-radius: 12px;
}

.hover-overlay p {
  color: white;
  font-weight: bold;
  margin: 0;
  padding: 0 15px;
  height: auto;
}

.pet-item:hover .hover-overlay {
  opacity: 1;
}

.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
}

.pagination button {
  padding: 8px 20px;
  background-color: #4a7c59;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.pagination button:hover:not(:disabled) {
  background-color: #3a6a49;
}

.pagination button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.no-pets {
  margin: 40px 0;
  font-size: 1.2rem;
  color: #666;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

/* 宠物详情弹窗样式 */
.pet-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: flex-end;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}

.modal-content {
  background-color: white;
  width: 100%;
  max-width: 800px;
  border-radius: 15px 15px 0 0;
  padding: 20px;
  position: relative;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 -2px 20px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
}

.close-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  background: none;
  border: none;
  font-size: 1.8rem;
  cursor: pointer;
  color: #666;
  z-index: 10;
}

.modal-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 10px;
  margin-bottom: 15px;
}

.modal-info {
  padding: 0 10px;
}

.modal-info h2 {
  color: #4a7c59;
  margin-bottom: 15px;
  text-align: center;
}

.info-row {
  display: flex;
  margin-bottom: 10px;
  font-size: 0.95rem;
}

.info-label {
  font-weight: bold;
  color: #4a7c59;
  width: 60px;
}

.modal-description {
  margin: 20px 0;
  line-height: 1.6;
  color: #333;
}

.modal-adopt-btn {
  background-color: #4a7c59;
  color: white;
  border: none;
  padding: 12px 25px;
  border-radius: 8px;
  font-size: 1rem;
  cursor: pointer;
  width: 100%;
  margin-top: 15px;
  transition: all 0.3s;
}

.modal-adopt-btn:hover {
  background-color: #3a6a49;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

/* 响应式调整 */
@media (min-width: 768px) {
  .modal-content {
    /* flex-direction: row; */
    align-items: flex-start;
    padding: 30px;
    border-radius: 15px;
    margin-bottom: 50px;
  }

  .modal-image {
    width: 300px;
    height: 300px;
    margin-right: 30px;
    margin-bottom: 0;
  }
}

@media (max-width: 768px) {
  .filters {
    flex-direction: column;
    align-items: center;
  }

  .filter-group {
    width: 100%;
    max-width: 250px;
    margin-bottom: 10px;
  }

  .pet-list {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  }

  .pet-adoption {
    padding: 15px;
  }
}

@media (max-width: 480px) {
  .pet-list {
    grid-template-columns: 1fr;
  }

  h1 {
    font-size: 1.8rem;
  }

  .pagination {
    flex-direction: column;
    gap: 10px;
  }

  .pet-actions {
    flex-direction: column;
    align-items: center;
  }

  .favorite-btn {
    margin-top: 8px;
  }
}

.adoption-form {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.adoption-form h3 {
  color: #4a7c59;
  margin-bottom: 15px;
  text-align: center;
}

.form-group {
  margin-bottom: 15px;
}

.form-group.full-width {
  width: 100%;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  color: #555;
}

input,
select,
textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 0.95rem;
}

textarea {
  min-height: 100px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  font-weight: normal;
}

.checkbox-label input {
  width: auto;
  margin-right: 10px;
}

.checkbox-label a {
  color: #4a7c59;
  text-decoration: none;
  margin-left: 5px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
}

.error-message {
  color: #ff6b6b;
  font-size: 0.8em;
  margin-top: 5px;
  display: block;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: normal;
  cursor: pointer;
}

.checkbox-label input {
  width: auto;
}

.cancel-btn,
.submit-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
}

.cancel-btn {
  background-color: #f1f1f1;
  color: #666;
}

.submit-btn {
  background-color: #4a7c59;
  color: white;
}

/* 领养协议弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  width: 90%;
  max-width: 600px;
  border-radius: 15px;
  padding: 30px;
  position: relative;
}

.agreement-text {
  margin: 20px 0;
  line-height: 1.8;
}

.agree-btn {
  display: block;
  width: 100%;
  padding: 12px;
  background-color: #4a7c59;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
}

/* 在PetAdoption的style部分添加 */
.pet-item.lost {
  border: 2px solid #ff6b6b;
  position: relative;
}

.pet-item.lost::after {
  content: "丢失";
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #ff6b6b;
  color: white;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
}
</style>